﻿using System.Windows;
using System.Windows.Controls.WpfPropertyGrid;
using Microsoft.Win32;
using System.Windows.Input;
using System.Configuration;
using System.IO;
using System;

namespace devtm.Editor.Configuration.MyEditors
{

    public enum EditorType
    {
        Save,
        Open
    }

    public class FilePathPicker : PropertyEditor, ICommand
    {
        public FilePathPicker()
        {
            this.InlineTemplate = UCConfigEdit.ConfigEdit.TryFindResource(EditorKeys.FilePathPickerEditorKey) ?? EditorKeys.FilePathPickerEditorKey;
        }

        public string Filter { get; set; }
        public EditorType TypeDialog { get; set; }

        


        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event System.EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (TypeDialog == EditorType.Save)
                Save((PropertyItemValue)parameter);
            else
                Open((PropertyItemValue)parameter);
            
        }

        private void Open(PropertyItemValue propertyValue)
        {
            if (propertyValue == null) return;
            if (propertyValue.ParentProperty.IsReadOnly) return;

            OpenFileDialog ofd = new OpenFileDialog
            {
                Filter = Filter,
                Multiselect = false
            };

            if (ofd.ShowDialog() == true)
                propertyValue.StringValue = ofd.FileName;
        }

        private void Save(PropertyItemValue propertyValue)
        {

            PropertiesSection info = (PropertiesSection)propertyValue.ParentProperty.Component;
            
            if (propertyValue == null) return;
            if (propertyValue.ParentProperty.IsReadOnly) return;

            SaveFileDialog ofd = new SaveFileDialog
            {
                Filter = Filter
            };

            if (ofd.ShowDialog() == true)
            {
                FileInfo f = new FileInfo(info.ConfigurationSection().ElementInformation.Source);

                Uri source = new Uri(f.Directory.FullName + @"\");
                Uri destination = new Uri(ofd.FileName);

                string name = source.MakeRelativeUri(destination).ToString().Replace("/", @"\");

                try
                { propertyValue.Value = name; }

                catch (Exception e)
                { MessageBox.Show(e.Message, "Error setting value", MessageBoxButton.OK, MessageBoxImage.Warning); }

                info.ForceSave = true;

            }
        }

    }

}
